package cn.anc.aonicardv.module.ui.recorder;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.anc.aonicardv.Constant;
import cn.anc.aonicardv.R;
import cn.anc.aonicardv.bean.AlbumBean;
import cn.anc.aonicardv.bean.PhotoBean;
import cn.anc.aonicardv.bean.VideoBean;
import cn.anc.aonicardv.event.AllSelectEvent;
import cn.anc.aonicardv.event.DeleteEvent;
import cn.anc.aonicardv.event.DownLoadEvent;
import cn.anc.aonicardv.event.MoveEvent;
import cn.anc.aonicardv.event.PlayVideoDataEvent;
import cn.anc.aonicardv.event.RecorderShareEvent;
import cn.anc.aonicardv.event.RecorderVideoDataEvent;
import cn.anc.aonicardv.module.adpter.listener.OnAlbumItemClickListener;
import cn.anc.aonicardv.module.adpter.listener.OnAlbumItemLongClickListener;
import cn.anc.aonicardv.module.adpter.recorder.RecorderVideoAdapter;
import cn.anc.aonicardv.module.ui.base.BaseFragment;
import cn.anc.aonicardv.util.ActivityUtils;
import cn.anc.aonicardv.util.DateUtils;
import cn.anc.aonicardv.util.DialogUtils;
import cn.anc.aonicardv.util.FileUtils;
import cn.anc.aonicardv.util.ListUtils;
import cn.anc.aonicardv.util.LogUtil;
import cn.anc.aonicardv.util.SpUtils;
import cn.anc.aonicardv.util.ViewUtil;
import cn.anc.aonicardv.widget.AlbumDecoration;
import cn.anc.aonicardv.widget.RecorderAlbumDownloadDialog;
import cn.anc.httpcontrolutil.CarControl;
import cn.anc.httpcontrolutil.CarControlCommand;
import cn.anc.httpcontrolutil.cache.CacheManager;

/**
 * Created by yangdai on 2017/5/18.
 */

public class RecorderVideoFragment extends BaseFragment implements CarControl.OnCardvThumbnailCallback, OnAlbumItemClickListener, CarControl.OnCarControlCallback, OnAlbumItemLongClickListener, DialogInterface.OnDismissListener, View.OnClickListener {

    private static String TAG = RecorderVideoFragment.class.getSimpleName();
    private RecyclerView videoRv;
    private RecorderVideoAdapter videoAdapter = null;
    private List<VideoBean> videoBeanList = null;
    private List<VideoBean> currentPhotoBeanList = null;
    private List<AlbumBean> result;
    private List<VideoBean> deletedVideos = null;
    private List<String> deletedPaths = null;
    private AlbumDecoration decoration;
    private int startIndex;
    private List<VideoBean> downloadVideoBeans = new ArrayList<>();
    public List<AlbumDecoration.DecorationBean> decorationBeanList;
    private RecorderAlbumActivity recorderAlbumActivity;
    private ProgressDialog progressDialog;
    private boolean isSharing;
    private RecorderAlbumDownloadDialog albumDownloadDialog;
    private DialogUtils dialogUtils;
    private GridLayoutManager gridLayoutManager;
    private int delete_num = 10;
    private Handler mHandler = new Handler();
    private View mLayoutNoDataView;
    private int mPage = 1;
    private int mPageNumber = 6;
    private int mRowNumber = 3;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return initView(R.layout.fragment_recorder_video);
    }

    @Override
    public void initVariable() {
        recorderAlbumActivity = (RecorderAlbumActivity) getActivity();
        dialogUtils = new DialogUtils();
        progressDialog = dialogUtils.getProgressDialog(getActivity());
        gridLayoutManager = null;
    }

    private LinearLayout mLlRootData;
    private TextView mTvUp, mTvDowm, mTvPage;

    @Override
    public void findViewById(View view) {
        mLlRootData = view.findViewById(R.id.ll_root_data);
        mTvPage = view.findViewById(R.id.tv_page);
        mTvUp = view.findViewById(R.id.tv_up);
        mTvUp.setOnClickListener(this);
        mTvDowm = view.findViewById(R.id.tv_dowm);
        mTvDowm.setOnClickListener(this);

        mLayoutNoDataView = view.findViewById(R.id.layout_no_data_view);
        videoRv = view.findViewById(R.id.rv_video);
    }


    @Override
    public void setListener() {


    }

    private void loadVideoThumbs() {
        if (currentPhotoBeanList == null || currentPhotoBeanList.isEmpty() || videoRv == null)
            return;
        int start, end;
        start = gridLayoutManager.findFirstVisibleItemPosition();
        end = gridLayoutManager.findLastVisibleItemPosition();
        int size = currentPhotoBeanList.size() - 1;
        if (start < 0)
            start = 0;
        if (end < 0)
            end = size >= 14 ? 14 : size;
        List<Integer> idxArray = new ArrayList<>();
        for (int i = start; i <= end; i++) {
            if (!CacheManager.checkCacheExist(currentPhotoBeanList.get(i).getPath())) {
                idxArray.add(i);
            } else if (!currentPhotoBeanList.get(i).isLoadStatus()) {
                videoAdapter.notifyItemChanged(i);
            }
        }
        CarControl.doGetVideoThumbnail(currentPhotoBeanList, idxArray, RecorderVideoFragment.this);
    }

    @Override
    public void initData() {

        if (null != CarControl.DeviceInfo.chip) {

            if (CarControl.DeviceInfo.chip.equals("LT")) {
                delete_num = 5;
            } else if (CarControl.DeviceInfo.chip.equals("MSTAR")) {
                delete_num = 3;
            }
        }
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(AllSelectEvent event) {
        if (videoBeanList == null || !getUserVisibleHint()) {
            return;
        }
        for (VideoBean p : videoBeanList) {
            p.setCheck(event.isAllSelect);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MoveEvent event) {
        if (isReturn()) {
            return;
        }
        deletedVideos = new ArrayList<>();
        deletedPaths = new ArrayList<>();
        for (VideoBean v : videoBeanList) {
            if (v.isCheck()) {
                deletedPaths.add(v.getPath());
                deletedVideos.add(v);
            }
        }
        startIndex = 0;
        moveFileByCount(deletedPaths, startIndex);
        progressDialog.setMessage(getString(R.string.recorder_album_move_file_hint));
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(DeleteEvent event) {
        if (isReturn()) {
            return;
        }
        deletedVideos = new ArrayList<>();
        deletedPaths = new ArrayList<>();
        for (VideoBean v : videoBeanList) {
            if (v.isCheck()) {
                deletedPaths.add(v.getPath());
                deletedVideos.add(v);
            }
        }
        startIndex = 0;
        deleteFileByCount(deletedPaths, startIndex);
        progressDialog.setMessage(getString(R.string.recorder_album_delete_file_hint));
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    private boolean isReturn() {
        return videoBeanList == null || videoBeanList.isEmpty() || !getUserVisibleHint();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(DownLoadEvent event) {
        if (isReturn()) {
            return;
        }
        for (VideoBean v : videoBeanList) {
            if (v.isCheck() && v.getDownloadStatus() == PhotoBean.DownLoadStatus.NO_DOWNLOADED) {
                v.setDownloadStatus(PhotoBean.DownLoadStatus.WAITING_DOWNLOADED);
                downloadVideoBeans.add(v);
            }
        }
        if (downloadVideoBeans.isEmpty())
            return;
        albumDownloadDialog = new RecorderAlbumDownloadDialog(getActivity(), R.style.BaseDialogStyle, RecorderAlbumDownloadDialog.TYPE_VIDEO, isSharing, downloadVideoBeans) {
            @Override
            public void sharePhoto(String path) {

            }
        };
        albumDownloadDialog.setOnDismissListener(this);
        albumDownloadDialog.show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RecorderShareEvent event) {
        if (isReturn()) {
            return;
        }
        String sharePath = null;
        for (VideoBean v : videoBeanList) {
            if (v.isCheck() && v.getDownloadStatus() == PhotoBean.DownLoadStatus.COMPLETE_DOWNLOADED) {
                sharePath = v.getPath();
                break;
            }
        }
        if (TextUtils.isEmpty(sharePath)) {
            isSharing = true;
            onMessageEvent(new DownLoadEvent());
        }
    }

    private void moveFileByCount(List<String> temp, int startIndex) {
        LogUtil.e("llcTest", "-------moveFileByCount-----:" + temp.size());
        if (temp.size() > 0 && temp.size() <= delete_num) {
            CarControl.doMoveFile(CarControlCommand.CarMediaType.CAR_MEDIA_TYPE_NORMAL_VIDEO, temp, this);
        } else {
            int remain = temp.size() % delete_num;
            if (temp.size() - startIndex == remain) {
                CarControl.doMoveFile(CarControlCommand.CarMediaType.CAR_MEDIA_TYPE_NORMAL_VIDEO, ListUtils.subList(temp, startIndex, temp.size() - 1), this);
            } else {
                CarControl.doMoveFile(CarControlCommand.CarMediaType.CAR_MEDIA_TYPE_NORMAL_VIDEO, ListUtils.subList(temp, startIndex, startIndex + delete_num - 1), this);
            }
        }
    }

    private void deleteFileByCount(List<String> temp, int startIndex) {
        if (temp.size() > 0 && temp.size() <= delete_num) {
            CarControl.doDeleteFile(CarControlCommand.CarMediaType.CAR_MEDIA_TYPE_NORMAL_VIDEO, temp, this);
        } else {
            int remain = temp.size() % delete_num;
            if (temp.size() - startIndex == remain) {
                CarControl.doDeleteFile(CarControlCommand.CarMediaType.CAR_MEDIA_TYPE_NORMAL_VIDEO, ListUtils.subList(temp, startIndex, temp.size() - 1), this);
            } else {
                CarControl.doDeleteFile(CarControlCommand.CarMediaType.CAR_MEDIA_TYPE_NORMAL_VIDEO, ListUtils.subList(temp, startIndex, startIndex + delete_num - 1), this);
            }
        }
    }

    private void refreshUi() {
        if (videoBeanList == null || videoBeanList.isEmpty()) {
            ViewUtil.showContentLayout(Constant.LAYOUT_EMPTY, mLayoutNoDataView, mLlRootData, R.mipmap.video_empty, getActivity().getResources().getString(R.string.video_empty_hint));

        } else {
            ViewUtil.showContentLayout(Constant.LAYOUT_DATA, mLayoutNoDataView, mLlRootData);
            currentPhotoBeanList = listSplitOfPage(videoBeanList);
        if (videoAdapter == null) {
            videoAdapter = new RecorderVideoAdapter(currentPhotoBeanList, this,mRowNumber);
            videoAdapter.registerEventBusForAdapter();
            videoAdapter.setOnItemClickListener(this);
            videoAdapter.setOnItemLongClickListener(this);
        } else {
            videoAdapter.refreshDataList(currentPhotoBeanList);
        }
        videoRv.setAdapter(videoAdapter);
        setDecoration();
        loadVideoThumbs();
        }
    }

    private List<VideoBean> listSplitOfPage(List<VideoBean> photoBeanList) {
        List<VideoBean> mBeanList = new ArrayList<>();

        if (null == photoBeanList || photoBeanList.size() == 0 || mPage < 1) {
            mPage = 1;
        } else {
            //获取总页数
            int maxPage = photoBeanList.size() / mPageNumber;
            if (maxPage * mPageNumber < photoBeanList.size()) {
                maxPage++;
            }
            mMaxPage = maxPage;
            if (mPage > maxPage) {
                mPage = maxPage;
            }
            mTvPage.setText(mPage + "/" + mMaxPage);
            //通过当前页码获取当前应该显示的数据list
            int index = 0;
            for (int i = 0; i < mPageNumber; i++) {
                index = (mPage - 1) * mPageNumber + i;
                if (index < photoBeanList.size()) {
                    mBeanList.add(photoBeanList.get(index));
                } else {
                    break;
                }
            }


        }


        return mBeanList;

    }

    private void setDecoration() {
        result = AlbumBean.getClassifyAlbumBeanByVideoBean(videoBeanList);
        decorationBeanList = getDecorationBeanByAlbumBean(result);
        if (gridLayoutManager == null) {
            gridLayoutManager = new GridLayoutManager(getContext(), mRowNumber);

            videoRv.setLayoutManager(gridLayoutManager);
        }

    }

    private List<AlbumDecoration.DecorationBean> getDecorationBeanByAlbumBean(List<AlbumBean> result) {
        List<AlbumDecoration.DecorationBean> temp = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            AlbumDecoration.DecorationBean d = new AlbumDecoration.DecorationBean(result.get(i).getPosition(), result.get(i).getDate(), result.get(i).getVideoBeanList().size());
            temp.add(d);
        }
        return temp;
    }

    public int getVideoNum() {
        return videoBeanList == null ? 0 : videoBeanList.size();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (videoBeanList != null)
            refreshUi();
    }

    private long lastTime = 0;
    //将List按照时间倒序排列

    private long getNumOfName(String mBeanName) {
        if (mBeanName != null) {
            try {
                String name = mBeanName.replace("_", "").replace("-", "").replace(":", "").replace(" ", "");
                long a = Long.parseLong(name);
                return a;
            } catch (Exception e) {

            }
        }
        return 0;

    }

    public void invertOrderList(List<VideoBean> mDataList) {
        Collections.sort(mDataList, new Comparator<VideoBean>() {
            /*
             * int compare(Student o1, Student o2) 返回一个基本类型的整型，
             * 返回负数表示：o1 小于o2，
             * 返回0 表示：o1和o2相等，
             * 返回正数表示：o1大于o2。
             */
            public int compare(VideoBean o1, VideoBean o2) {
                //按照时间大小进行降序排列
                if (getNumOfName(o1.getName()) < getNumOfName(o2.getName())) {
                    return 1;
                }
                if (getNumOfName(o1.getName()) == getNumOfName(o2.getName())) {
                    return 0;
                }
                return -1;
            }
        });

    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageEvent(RecorderVideoDataEvent event) {
        if (event.videoBeanList != null) {
            videoBeanList = event.videoBeanList;
            lastTime = DateUtils.getCurrentDateTimeNills();
            invertOrderList(videoBeanList);
            mPage = 1;
            setMaxPage();
            mTvPage.setText(mPage + "/" + mMaxPage);
            refreshUi();
        }

    }


    private void setMaxPage() {
        //获取总页数
        int maxPage = videoBeanList.size() / mPageNumber;
        if (maxPage * mPageNumber < videoBeanList.size()) {
            maxPage++;
        }
        mMaxPage = maxPage;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (getUserVisibleHint() && resultCode == 200) {
            resetItemPosition();
            refreshUi();
        }
    }

    private void resetItemPosition() {
        for (int i = 0; i < videoBeanList.size(); i++) {
            videoBeanList.get(i).setItemPosition(i);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (videoAdapter != null)
            videoAdapter.unregisterEventBusForAdapter();
    }

    @Override
    public void OnThumbnailGetted(int index) {
        if (index<videoBeanList.size()){
        videoBeanList.get(index).setLoadStatus(true);
        videoAdapter.notifyItemChanged(index);
        }
    }

    @Override
    public void onItemClick(CheckBox c, int position, boolean isEditMode) {
        if (!isEditMode) {
            int clickposition = (mPage - 1) * mPageNumber + position;
            LogUtil.e("llcTest", "-------1111111111-----:" + clickposition);
            ActivityUtils.jumpActivityForResult(getActivity(), RecorderPlayVideoActivity.class, new String[]{Constant.IntentKeyParam.POSITION, clickposition + "", Constant.IntentKeyParam.TYPE, cn.anc.aonicardv.module.ui.recorder.RecorderFragment.TYPE_NORMAL}, 10001);
            EventBus.getDefault().postSticky(new PlayVideoDataEvent(videoBeanList));
        } else {
            c.setPressed(true);
            if (c.isChecked()) {
                c.setChecked(false);
            } else
                c.setChecked(true);
            c.setPressed(false);
        }
    }

    private void removeDeletedPhotos() {
        videoBeanList.removeAll(deletedVideos);
        resetItemPosition();
        refreshUi();
    }

    @Override
    public void onItemLongClick(View view, int position, boolean isEditMode) {
        recorderAlbumActivity.select();
    }

    @Override
    public void OnCommandCallback(int code, CarControl.CommandResponseInfo info) {

        LogUtil.e("llcTest", "-------22333----info-:" + info.msg_id);
        if (code != 0) {
            return;
        }
        switch (info.msg_id) {
            case CarControlCommand.CAR_CONTROL_COMMAND_ID_DELETE_FILE:
                FileUtils.deleteLocalFile(deletedPaths, startIndex, delete_num);
                removeVideoSpInfo();
                startIndex += delete_num;
                if (startIndex < deletedPaths.size())
                    deleteFileByCount(deletedPaths, startIndex);
                else {
                    if (!isDetached()) {
                        progressDialog.dismiss();
                        Toast.makeText(getActivity(), getString(R.string.delete_success), Toast.LENGTH_SHORT).show();


                    }
                    removeDeletedPhotos();
                }
                break;
            case CarControlCommand.CAR_CONTROL_COMMAND_ID_MOVE_FILE:
                FileUtils.deleteLocalFile(deletedPaths, startIndex, delete_num);
                removeVideoSpInfo();
                startIndex += delete_num;
                if (startIndex < deletedPaths.size())
                    moveFileByCount(deletedPaths, startIndex);
                else {
                    if (!isDetached()) {
                        progressDialog.dismiss();
                        Toast.makeText(getActivity(), getString(R.string.move_success), Toast.LENGTH_SHORT).show();


                    }
                    removeDeletedPhotos();
                }
                break;
            default:
                break;
        }
    }

    private void removeVideoSpInfo() {
        for (int i = 0; i < deletedPaths.size(); i++) {
            SpUtils.remove(deletedPaths.get(i));
        }
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        for (int i = 0; i < downloadVideoBeans.size(); i++) {
            videoAdapter.notifyItemChanged(downloadVideoBeans.get(i).getItemPosition());
        }
        downloadVideoBeans.clear();
    }

    private int mMaxPage = 0;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_up:
                if (mPage > 1 && mMaxPage > 0 && mPage <= mMaxPage) {
                    mPage--;
                    refreshUi();
                }
                break;
            case R.id.tv_dowm:
                if (mMaxPage > 0 && mPage < mMaxPage) {
                    mPage++;
                    refreshUi();
                }
                break;

        }
    }
}
